package cn.jasonone.ueditor.storage;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;

import com.baidu.ueditor.define.AppInfo;
import com.baidu.ueditor.define.BaseState;
import com.baidu.ueditor.define.MultiState;
import com.baidu.ueditor.define.State;

import cn.jasonone.ueditor.Item;
import cn.jasonone.ueditor.upload.UeditorStorage;
import lombok.Data;
/**
 * 本地文件持久化类
 * @author Jason
 *
 */
@Component
@Data
public class LocationFileStorage implements UeditorStorage {
	private String rootPath;
	private String[] allowFiles;
	private String dir;
	private Integer count;

	/**
	 * 检测用于对于path是否拥有写权限
	 * 
	 * @param savePath 保存路径
	 * @return 处理结果
	 */
	public BaseState validFile(String savePath) {
		File file = new File(rootPath, savePath);
		File parentPath = file.getParentFile();

		if ((!parentPath.exists()) && (!parentPath.mkdirs())) {
			return new BaseState(false, AppInfo.FAILED_CREATE_FILE);
		}

		if (!parentPath.canWrite()) {
			return new BaseState(false, AppInfo.PERMISSION_DENIED);
		}

		return new BaseState(true);
	}

	public void save(File file, String rootPath, String path) throws IOException {
		FileUtils.moveFile(file, new File(rootPath, path));
	}

	public void save(byte[] data, String rootPath, String savePath) throws IOException {
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(rootPath, savePath)));
		bos.write(data);
		bos.flush();
		bos.close();
	}

	@Override
	public State listFile(int index) {
		File dir = new File(this.dir);
		State state = null;

		if (!dir.exists()) {
			return new BaseState(false, AppInfo.NOT_EXIST);
		}

		if (!dir.isDirectory()) {
			return new BaseState(false, AppInfo.NOT_DIRECTORY);
		}
		if(this.allowFiles == null) {
			this.allowFiles=this.getAllowFiles(getAllowFiles());
		}
		Collection<File> list = FileUtils.listFiles(dir, this.allowFiles, true);

		if (index < 0 || index > list.size()) {
			state = new MultiState(true);
		} else {
			List<File> fileList=new ArrayList<>(list);
			fileList=fileList.subList(index, index + this.count);
			state = this.getState(this.rootPath,Item.asList(fileList));
		}
		state.putInfo("start", index);
		state.putInfo("total", list.size());
		return state;
	}
}
